package com.featherlike.feather.generator.engine;

import java.io.FileWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.featherlike.feather.generator.config.Constant;
import com.featherlike.framework.common.util.ClassUtil;
import com.featherlike.framework.common.util.Exceptions;
import com.featherlike.framework.common.util.FileUtil;
import com.featherlike.framework.common.util.IOUtil;
import com.featherlike.framework.common.util.StringUtil;

public class VelocityImpl implements ITemplateEngine {
	private static final Logger logger = LoggerFactory
			.getLogger(VelocityImpl.class);
	private static final VelocityEngine engine = new VelocityEngine();

	// 设置 VM 文件加载路径（默认为 classpath）
	public VelocityImpl(String tmplPath) {
		Properties props = new Properties();
		props.setProperty(Velocity.INPUT_ENCODING, Constant.ENCODING_UTF8);// 设置输入字符集
		props.setProperty(Velocity.OUTPUT_ENCODING, Constant.ENCODING_UTF8);// 设置输出字符集
		props.setProperty(Velocity.ENCODING_DEFAULT, Constant.ENCODING_UTF8);
		props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
				NullLogChute.class.getName());
		if (StringUtil.isEmpty(tmplPath)) {
			props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,
					ClassUtil.getClassPath());
		} else {
			props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, tmplPath);
		}
		engine.init(props);
	}

	// 合并模板到文件中
	public void mergeTemplateIntoFile(String vmPath,
			Map<String, Object> dataMap, String filePath) {
		FileWriter writer = null;
		try {
			if (FileUtil.createFile(filePath)) {
				Template template = engine.getTemplate(vmPath);
				VelocityContext context = new VelocityContext(dataMap);
				writer = new FileWriter(filePath);
				template.merge(context, writer);
				writer.close();
			} else {
				logger.info("文件已存在,生成失败");
			}
		} catch (Exception e) {
			logger.error("合并模板出错！", e);
			throw Exceptions.unchecked(e);
		} finally {
			IOUtil.closeQuietly(writer);
		}
	}

	// 合并模板并返回字符串
	public String mergeTemplateReturnString(String vmPath,
			Map<String, Object> dataMap) {
		String result;
		StringWriter writer = null;
		try {
			Template template = engine.getTemplate(vmPath, "ISO-8859-1");
			VelocityContext context = new VelocityContext(dataMap);
			writer = new StringWriter();
			template.merge(context, writer);
			result = writer.toString();

			writer.close();
		} catch (Exception e) {
			logger.error("合并模板出错！", e);
			throw Exceptions.unchecked(e);
		} finally {
			IOUtil.closeQuietly(writer);
		}
		return result;
	}

	@Override
	public String getTemplateSuffix() {
		return Constant.VM_SURFIX;
	}
}
